package cn.wolfcode.wolf2w.advice;

import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.util.JsonResult;
import javafx.fxml.LoadException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

//（自定义异常和系统异常）做统一异常处理
/*ControllerAdvice是Controller功能增强注解
        作用：在请求进入映射方法前,做功能增强:经典用法: Date类型参数格式化
        在请求进入映射方法后,做功能增强:经典用法:统一异常处理
      */
@ControllerAdvice
public class CommonExceptionHandler {
    @ResponseBody
    //处理的是什么异常
    @ExceptionHandler(LogicException.class)
    public Object handlerLogicException(Exception e, HttpServletResponse resp) {
        e.printStackTrace();
        resp.setContentType("application/json;charset=utf-8");
        //自定义给用户的异常
        return JsonResult.error(JsonResult.CODE_ERROR_PARAM, e.getMessage(), null);
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handlerLoadDefaultException(Exception e,HttpServletResponse resp) {
        //系统异常
        e.printStackTrace();
        resp.setContentType("application/json;charset=utf-8");
        return JsonResult.defaultError();
    }
}
